<template>
    <div class="category-container">
        <!-- 顶部操作栏 -->
        <div class="top-bar">
            <div class="search-area">
                <el-input v-model="searchForm.keyword" placeholder="输入库位名称查询"
                    style="width: 200px; margin-right: 10px;" />
                <el-checkbox v-model="searchForm.status" @change="handleCheck"
                    style="margin-left: 20px;">显示禁用库位</el-checkbox>
                <el-button type="primary" @click="searchWarehouseLocation">查询</el-button>
            </div>

            <div class="action-buttons">
                <el-button class="!ml-0" type="primary" @click="openAddDialog">新增</el-button>
                <el-button>禁用</el-button>
                <el-button>启用</el-button>
                <el-button>刷新</el-button>
            </div>

            <el-dialog v-model="dialogFormVisible" :title="dialogType === 'add' ? '新增库位' : '编辑库位'" width="500">
                <el-form :model="form" label-position="left">
                    <el-form-item label="所属仓库" :label-width="formLabelWidth">
                        <el-select v-model="form.warehouseCode" style="width: 240px" @change="onWarehouseChange">
                            <el-option v-for="item in warehouseList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="上级库位" :label-width="formLabelWidth">
                        <el-tree-select v-model="form.parentId" :data="treeSelectData"
                            :filter-node-method="filterNodeMethod" filterable style="width: 240px"
                            :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true"
                            clearable>
                            <template #default="{ data }">
                                <span>
                                    <el-icon>
                                        <Folder v-if="data.children && data.children.length > 0" />
                                        <Document v-else />
                                    </el-icon>
                                    {{ data.name }}
                                </span>
                            </template>
                        </el-tree-select>
                    </el-form-item>

                    <el-form-item label="库位编号" :label-width="formLabelWidth">
                        <el-input v-model="form.code" autocomplete="off" style="width: 240px" />
                    </el-form-item>

                    <el-form-item label="库位名称" :label-width="formLabelWidth">
                        <el-input v-model="form.name" autocomplete="off" style="width: 240px" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="saveType">确认</el-button>
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>

        <!-- 数据表格 -->
        <el-table :data="treeData" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="warehouseCode" label="所属仓库" width="150">
                <template #default="{ row }">
                    {{ row.warehouseName }}
                </template>
            </el-table-column>
            <el-table-column prop="name" label="库位名称" width="150" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
                        @change="() => handleStatusChange(row)" />
                </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="updateWarehouseLocation(row)">
                        <el-icon>
                            <Edit />
                        </el-icon>
                    </el-button>
                    <el-button size="small" @click="deleteWarehouseLocation(row)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, defineExpose } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const searchForm = reactive({
    keyword: '',
    status: 1,
})

// 库位
const warehouseLocationList = ref([])
const getWarehouseLocationList = async () => {

    try {
        const res = await axios.get('/api/basic/warehouse/allWarehouseLocation', {
            params: { ...searchForm }
        })
        if (res.data.code === 5200) {
            warehouseLocationList.value = res.data.warehouseLocationList
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        console.error('获取库位列表失败:', error)
        ElMessage.error('加载库位列表失败')
    }
}

const handleCheck = (checked) => {
    searchForm.status = checked ? null : 1
    getWarehouseLocationList()
}


// 修改 treeData 的 computed
const treeData = computed(() => {
    const map = {}
    const roots = []

    // 先克隆并初始化 level
    warehouseLocationList.value.forEach(item => {
        map[item.id] = { ...item, children: [], level: 1 } // 根节点默认 level=1
    })

    // 建立父子关系
    warehouseLocationList.value.forEach(item => {
        if (item.parentId === null || item.parentId === 0) {
            roots.push(map[item.id])
        } else {
            const parent = map[item.parentId]
            if (parent) {
                map[item.id].level = parent.level + 1 // 子节点 level = 父 level + 1
                parent.children.push(map[item.id])
            }
        }
    })

    return roots
})


// 树形选择器
const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 搜索
const searchWarehouseLocation = () => {
    getWarehouseLocationList()
}

// ====== 表单 & 对话框 ======
const dialogFormVisible = ref(false)
const dialogType = ref('add')
const formLabelWidth = '80px'

const form = ref({
    id: '',
    warehouseCode: '',
    companyCode: '',
    code: '',
    parentId: '',
    name: ''
})

// 获取所有仓库
const warehouseList = ref([])
const getWarehouseList = async () => {
    const res = await axios.get('/api/basic/warehouse/allWarehouses')

    if (res.data.code === 5200) {
        warehouseList.value = res.data.warehouseList
    }
}

// ====== 方法 ======
const openAddDialog = () => {
    form.value = { warehouseCode: '', companyCode: '', code: '', parentId: '', name: '' }
    dialogFormVisible.value = true
}

const onWarehouseChange = () => {
    form.value.parentId = '' // 切换仓库清空上级
}

const filterNodeMethod = (query, data) => {
    if (!query) return true
    return data.name.includes(query)
}

// 保存（新增/编辑）
const saveType = async () => {

    try {
        let res
        if (dialogType.value === 'add') {
            res = await axios.post('/api/basic/warehouse/addWarehouseLocation', form.value)
        } else {
            res = await axios.post('/api/basic/warehouse/updateWarehouseLocation', form.value)
        }

        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getWarehouseLocationList()
            dialogFormVisible.value = false
        } else {
            ElMessage.error(res.data.msg || '操作失败')
        }
    } catch (error) {
        ElMessage.error('请求失败：' + (error.response?.data?.msg || error.message))
    }
}

// 编辑
const updateWarehouseLocation = async (row) => {
    dialogType.value = 'edit'

    const res = await axios.get('/api/basic/warehouse/warehouseLocationById', null, { params: { id: row.id } })

    if (res.data.code === 5200) {
        form.value = res.data.warehouseLocation
        dialogFormVisible.value = true
    } else {
        ElMessage.error('获取数据失败')
    }
}

// 删除
const deleteWarehouseLocation = async (row) => {

    if (row.children && row.children.length > 0) {
        ElMessage.warning('该库位下存在子库位，无法删除')
        return
    }

    try {
        ElMessageBox.confirm("确定删除吗？此操作不可恢复")

        const res = await axios.post('/api/basic/warehouse/deleteWarehouseLocation', null, {
            params: { id: row.id }
        })

        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除操作出错')
        }
    }
}

// 状态切换
const handleStatusChange = async (row) => {
    const originalStatus = row.status
    try {
        const res = await axios.post('/api/basic/warehouse/updateWarehouseLocationStatus', null, {
            params: {
                id: row.id,
                status: originalStatus === 1 ? 0 : 1
            }
        })
        if (res.data.code !== 5200) {
            ElMessage.error('状态更新失败')
        } else {
            ElMessage.success('状态更新成功')
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试')
    }
}


// 暴露给外部使用的响应式变量（比如父组件要用）
const selectedThirdLevelNode = ref(null)

const handleSelectionChange = (selection) => {
    // 过滤出 level === 3 的节点
    const thirdLevelNodes = selection.filter(row => row.level === 3)

    // 取第一个（或 null）
    selectedThirdLevelNode.value = thirdLevelNodes.length > 0 ? thirdLevelNodes[0] : null

    console.log('当前选中的第三层节点:', selectedThirdLevelNode.value)
}

defineExpose({
    selectedThirdLevelNode,
    // 或者提供一个 getter 方法
    getSelectedThirdLevelNode: () => selectedThirdLevelNode.value
})

// 初始化
onMounted(() => {
    getWarehouseLocationList()
    getWarehouseList()
})
</script>

<style scoped>
.category-container {
    padding: 20px;
    background-color: #fff;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.el-table {
    margin-top: 10px;
}

.el-table .el-table__row:nth-child(even) {
    background-color: #f5f7fa;
}

.el-table .el-table__row>td:nth-child(3) {
    padding-left: 20px;
}
</style>